import Vue from "vue";
import Vuex from "vuex";
import createPersiste from 'vue-savedata'
console.log("createPersiste====>",createPersiste)

Vue.use(Vuex);
const state = {
  allRoutes:null,
  routesKeyAndName:null,
  count: 0,
  mutationData:'testtest',
  products: [
    {name: '鼠标', price: 20},
    {name: '键盘', price: 40},
    {name: '耳机', price: 60},
    {name: '显示屏', price: 80}
  ]
};
const getters = {
  saleProducts: (state) => {
    let saleProducts = state.products.map( product => {
      return {
        name: product.name,
        price: product.price / 2
      }
    })
    return saleProducts;
  }
};
const mutations={
  increment (state) {
    state.count++
  },
  mutationTest (state,data) {
    state.mutationData=data
  },
  setRoutesKey (state,data) {
    state.routesKeyAndName=data
  },
  minusPrice (state, payload ) {
    console.log("minusPrice====>",state, payload )
    let newPrice = state.products.forEach( product => {
      product.price -= payload
    })
     console.log("store newPrice",newPrice)
  },
  getRoutes (state, data ) {
     state.allRoutes=data
  }
}
const actions = {
  //和mutations对应
  minusPriceAsync( context, data ) {
    setTimeout( () => {
      context.commit( 'minusPrice', data ); //context提交
    }, 2000)
  },
  routesInfo({state}) {
    let routes = {
      children: this.$router.options.routes,
    };
    let route = this.$route.matched;
    for (let i = 0; i < route.length - 1; i++) {
      routes = routes.children.find((e) => e.name == route[i].name);
    }
    console.log("routes===vuex==", routes);
    state.routes = routes.children;
  },

};
const routerModules={

}
/* //定义需要保存的数据，LS即Localstorage本地存储, SS即sessionStorage本地存储
const persiste = createPersiste({
  ciphertext: true, // 加密存本地, 默认为false
  LS: {
      module: module1,
      // storePath: 'module100' // __storePath:(和Vuex中的option.modules:{key：value}的key,一,一对应)__
  },
  SS: {
      module: module2,
      // storePath: 'module2' 
  }
}) */
export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  routerModules,
  plugins: [createPersiste], //缓存所有store数据到本地 也可以单独缓存
});
